var express = require('express');
var passport = require('passport');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var config = require('../config/db')
const mongdb = require('mongodb')


/* 修改购物车 */
router.get('/updCart', function (req, res, next) {
    res.send('respond with a resource');
});




/*加入购物车 */
router.post('/addCarts', passport.authenticate('jwt', { session: false }),
    async function (req, res, next) {
        //获取加入购物车需要的商品信息
        let product = req.body.product
        //获取数据库连接对象
        let client = await MongoClient.connect(config.url)
        let db = client.db()
        //创建加入购物车对象
        let newCart = {
            "userId": req.user._id,
            "product": product,
            "num": 1,
            "addTime": new Date().toLocaleString()
        }
        // 提取id，查询购物车内当前所有记录包含的商品id
        //执行添加购物车的操作
        let results = await db.collection('cartTest').insertOne(newCart)
        console.log('results:', results)
        //判断是否添加成功
        if (results.acknowledged) {
            res.json({ code: 200, message: 'ok' });
        } else {
            res.json({ code: 200, message: 'error' })
        }
    })

/*展示购物车 */
router.get('/getCarts', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    //获取所有购物车商品数据
    let products = await db.collection('cartTest').find({ userId: req.user._id }).sort({ 'addTime': -1 }).toArray()
    console.log('carts:', products)
    if (products.length >= 0) {
        res.json({ code: 200, message: 'ok ', data: products });
    }
    else {
        res.json({ code: 200, message: 'error' });
    }
});

/*删除购物车*/
router.delete('/deleteCart', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    // 获取需要删除的购物车信息id
    let { id } = req.query
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    //执行删除购物车的操作
    let results = await db.collection('cartTest').deleteOne({ _id: new mongdb.ObjectId(id) })
    console.log('results:', results)
    //判断是否删除成功
    if (results.acknowledged) {
        res.json({
            code: 200, message: 'ok'
        });
    } else {
        res.json({
            code: 200, message: 'error'
        });
    }
});

/*批量删除购物车*/
router.delete('/deleteCarts', passport.authenticate('jwt', { session: false }), async function (req, res, next) {
    //获取需要删除的购物车信息id
    let { ids } = req.query
    let objIds = []
    ids.map(id => {
        objIds.push(new mongdb.ObjectId(id))
    })
    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    //执行删除购物车的操作
    let results = await db.collection('cartTest').deleteMany({ _id: { $in: objIds } })
    console.log('results:', results)
    //判断是否删除成功
    if (results.acknowledged) {
        res.json({ code: 200, message: 'ok' });
    } else {
        res.json({ code: 200, message: 'error' });
    }
});

/*清空购物车*/
router.delete('/deleteCartsAll', passport.authenticate('jwt', { session: false }), async function (req, res, next) {

    //获取数据库连接对象
    let client = await MongoClient.connect(config.url)
    let db = client.db()
    //执行清空购物车的操作
    let results = await db.collection('cartTest').deleteMany({ userId: req.user._id  })
    console.log('results:', results)
    //判断是否删除成功
    if (results.acknowledged) {
        res.json({ code: 200, message: 'ok' });
    } else {
        res.json({ code: 200, message: 'error' });
    }
});

module.exports = router;